package org.jeecg.glr.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.glr.domain.glr.GateWayTreeDomain;
import org.jeecg.glr.domain.glr.GlrGateWayControlLight;
import org.jeecg.glr.entity.GlrGateway;
import org.jeecg.glr.entity.GlrLight;
import org.jeecg.glr.entity.GlrLightType;
import org.jeecg.glr.service.IGateWayCommon;
import org.jeecg.glr.service.IGlrGatewayService;
import org.jeecg.glr.service.IGlrLightService;
import org.jeecg.glr.service.IGlrLightTypeService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 路灯管理
 * @Author: jeecg-boot
 * @Date: 2020-03-05
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrLight")
@Slf4j
public class GlrLightController extends JeecgController<GlrLight, IGlrLightService> {
    @Autowired
    private IGlrLightService glrLightService;
    @Autowired
    private IGlrGatewayService glrGatewayService;
    @Autowired
    private IGlrLightTypeService glrLightTypeService;

    @Value("${glr.url.light_gateway_get_light_date}")
    private String light_gateway_get_light_date;

    @Resource
    IGateWayCommon gateWayCommon;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 分页列表查询
     *
     * @param glrLight
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<?> queryPageList(GlrLight glrLight,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Map<String, String[]> parameterMap=new HashMap(req.getParameterMap());
        parameterMap.remove(QueryGenerator.ORDER_COLUMN);
        parameterMap.remove(QueryGenerator.ORDER_TYPE);
        QueryWrapper<GlrLight> queryWrapper = QueryGenerator.initQueryWrapperCode(glrLight, parameterMap);

        queryWrapper.orderByAsc("gate_way_code");
        queryWrapper.orderByAsc("code");
        Page<GlrLight> page = new Page<GlrLight>(pageNo, pageSize);
        IPage<GlrLight> pageList = glrLightService.page(page, queryWrapper);
        List<GlrLight> list=pageList.getRecords();
        for (GlrLight lg :
                list) {
            GlrLightType lgType=glrLightTypeService.getLightTypeByCode(lg.getLightTypeCode());
            GlrGateway gateway=  glrGatewayService.getGlrGatewayByCode(lg.getGateWayCode());
            lg.setGateWayName(gateway.getGatewayName());
            if(lgType!=null){
                lg.setTypeName(lgType.getName());
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param glrLight
     * @return
     */
    @AutoLog(value = "添加路灯",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody GlrLight glrLight) {
        glrLightService.saveLight(glrLight);
        int lightCount= glrGatewayService.getGlrDataWayLightCount(glrLight.getGateWayCode());
        redisUtil.putMapObject(GLRConstant.LIGHT_GATAWAY_CODE_LIGHT_REDIS,glrLight.getGateWayCode(),lightCount);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param glrLight
     * @return
     */
    @AutoLog(value = "修改路灯",logType= CommonConstant.LOG_TYPE_2)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody GlrLight glrLight) {
        glrLightService.updateEntityById(glrLight);
        int lightCount= glrGatewayService.getGlrDataWayLightCount(glrLight.getGateWayCode());
        redisUtil.putMapObject(GLRConstant.LIGHT_GATAWAY_CODE_LIGHT_REDIS,glrLight.getGateWayCode(),lightCount);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "删除路灯",logType= CommonConstant.LOG_TYPE_2)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        GlrLight glrLight= glrLightService.getById(id);
        int lightCount= glrGatewayService.getGlrDataWayLightCount(glrLight.getGateWayCode());
        redisUtil.putMapObject(GLRConstant.LIGHT_GATAWAY_CODE_LIGHT_REDIS,glrLight.getGateWayCode(),lightCount);
        glrLightService.removeEntityById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "删除路灯",logType= CommonConstant.LOG_TYPE_2)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.glrLightService.removeEntityByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        GlrLight glrLight = glrLightService.getById(id);
        if (glrLight == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(glrLight);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param glrLight
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrLight glrLight) {
        return super.exportXls(request, glrLight, GlrLight.class, "路灯管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(2);
            params.setNeedSave(true);
            try {
                Set<String> gatewaySet = new HashSet<String>();
                List<GlrLight> newList = new ArrayList<GlrLight>();
                List<GlrLight> list = ExcelImportUtil.importExcel(file.getInputStream(), GlrLight.class, params);
                for (GlrLight gl:
                        list) {
                   // gl.setType(GLRConstant.GLR_LIGHT_TYPE_1);
                    if(StringUtil.isNotEmpty(gl.getGateWayCode())&&StringUtil.isNotEmpty(gl.getProjectCode())){
                        gatewaySet.add(gl.getGateWayCode());
                        newList.add(gl);
                    }
                }

                /*
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                glrLightService.saveBatch(newList);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                Iterator<String> iterator=  gatewaySet.iterator();
                while (iterator.hasNext()) {
                    String code = iterator.next();
                   int lightCount= glrGatewayService.getGlrDataWayLightCount(code);
                    redisUtil.putMapObject(GLRConstant.LIGHT_GATAWAY_CODE_LIGHT_REDIS,code,lightCount);
                }
                //update-end-author:taoyan date:20190528 for:批量插入数据
                */

                //上面的改成这样，需要更新此灯杆对象中设备状态、增加此灯杆相关设备记录
                Iterator<GlrLight> iterator=  newList.iterator();
                while (iterator.hasNext()) {
                    GlrLight glrLight = iterator.next();
                    glrLightService.saveImportLight(glrLight);
                    int lightCount= glrGatewayService.getGlrDataWayLightCount(glrLight.getGateWayCode());
                    redisUtil.putMapObject(GLRConstant.LIGHT_GATAWAY_CODE_LIGHT_REDIS,glrLight.getGateWayCode(),lightCount);
                }







                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 获取网关树
     *
     * @return
     */
    @GetMapping(value = "/gateWayTree")
    public Result<?> gateWayTree(GlrGateway glrGateway,HttpServletRequest req) {
        QueryWrapper<GlrGateway> queryWrapper = QueryGenerator.initQueryWrapperCode(glrGateway, req.getParameterMap());
        List<GlrGateway> gatewayList = glrGatewayService.list(queryWrapper);
        GateWayTreeDomain parentdomain = new GateWayTreeDomain();
        parentdomain.setTitle("网关信息");
        parentdomain.setValue("");
        parentdomain.setKey("");
        List<GateWayTreeDomain> treeList = new ArrayList<>();
        for (GlrGateway glr : gatewayList) {
            GateWayTreeDomain domain = new GateWayTreeDomain();
            domain.setKey(glr.getGateWayCode());
            domain.setTitle(glr.getGatewayName());
            domain.setValue(glr.getGateWayCode());
            treeList.add(domain);

        }
        parentdomain.setChildren(treeList);
        return Result.ok(parentdomain);
    }

    /**
     * 读取路灯数据
     *
     * @param glrLight
     * @return
     */
    @PostMapping(value = "/readLightData")
    public Result<?> readLightData(@RequestBody GlrLight glrLight) {
        gateWayCommon.readLightData(glrLight.getGateWayCode());
        return Result.ok("操作成功");
    }
    /**
     *   修改经纬度
     *
     * @return
     */
    @AutoLog(value = "修改路灯经纬度",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/updateLg")
    public Result<?> updateLg(@RequestBody GlrLight glrLight) {
        glrLightService.updateById(glrLight);
        return Result.ok("操作成功");
    }


    /**
     *
     * 功能描述: 控制网关下的路灯开关
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/9 9:32
     */
    @AutoLog(value = "开关路灯操作",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/ledOpenOrClose")
    public Result<?> ledOpenOrClose(@RequestBody GlrLight glrLight) {
        String[] codes=glrLight.getLightCode().split(",");
        for(int i=0;i<codes.length;i++){
            //灯发送命令
            String[] code1=codes[i].split(";");
            GlrGateWayControlLight lg = new GlrGateWayControlLight();
            lg.setGateWayCode(code1[1]);
            lg.setBrightValue(glrLight.getBrightValue());
            lg.setLightCode(code1[0]);
            lg.setType(GLRConstant.GLR_GATE_WAY_CONTROL_LIGHT_TYPE_01);
            gateWayCommon.ledOpenOrClose(lg);
        }
        return Result.ok("操作成功！");
    }

    /**
     *
     * 功能描述: 控制网关下的路灯开关
     *
     * @param:
     * @return:
     * @auther: Administrator
     * @date: 2020/3/9 9:32
     */
    @PostMapping(value = "/aloneLedOpenOrClose")
    @AutoLog(value = "开关路灯操作",logType= CommonConstant.LOG_TYPE_2)
    public Result<?> aloneLedOpenOrClose(@RequestBody GlrLight glrLight) {
        String[] codes=glrLight.getLightCode().split(",");
        for(int i=0;i<codes.length;i++){
            //灯发送命令
            String[] code1=codes[i].split(";");
            String gateWayCode=code1[1];
            String lightCode=code1[0];
            GlrGateWayControlLight lg = new GlrGateWayControlLight();
            lg.setGateWayCode(gateWayCode);
            lg.setBrightValue(glrLight.getBrightValue());
            lg.setLightCode(lightCode);
            gateWayCommon.ledOpenOrClose(lg);
        }
        return Result.ok("操作成功！");
    }

}
